// var orderbill = require('../../js/shop/order.js').order
const chooseLocation = requirePlugin('chooseLocation');
var actmember = require('../../../xc/model/member');
var paytool = require('./js/paytool');

// var util = require('../../../utils/util.js');
var actcart = require('../../../xc/sys/cart')
var wsactcart = require('../../../xc/sys/purchaseorder')

var acttoolv2 = require('../../../xc/sys/toolv2')
var order_bill = require('../model/order_bill.js')
var actcouponbill = require('../../../xc/model/coupon_cont')
// var actpacklistbill = require('../../../model/pack_list')
var actpacklistbill = require('../model/pack_list')

import Notify from '../../../vant/weapp/notify/notify';
var app = getApp();
Page({
  mixins: [require('../../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    calcsamecityinfo: null,
    delivery_config: null,
    expressaddr: null,
    //订单默认参数
    paytype: -1, //支付类型1.微信支付
    // 导航
    nav: [],
    navCur: -1,
    deliverymode: 1, //navCur =0 的有效  1自提  2团长配送    
    activitymodel: {
      clienttimestampdeviation: 0, //服务器跟客户端 的时间误差
      haslimite: false,
      intervalid: -1 //自己执行判断   
    },
    priceinfo: {},
    freight: 0, //快递费   actcoupon  freight paytype expressaddr paytype deliverymode
    actcoupon: null,
    actclub: null,
    remark: "",
    iscart: "-1",
    memberinfo: null,
    paymentmethod: [],
    clubdelivery: 0, //1自提 2配送
    // balanceloadsuccess: false,
    pageshow: true,
    submitstatus: false, //提交按钮状态
    chosedtimeshow: false,
    delivertime: "",
    minDate: new Date().getTime(),
    currentDate: new Date().getTime(),
    packinfo: null,
    iconmode: '1',
    unit: '￥',
    templists: null
  },
  //加载完成加载
  xcloaddata: function (options, config) {


    var that = this;
    var app = getApp();

    this.setconfig(config)

    this.getTemplists()
    this.judgeorder()
    // this.sendnotice_buy('20210904140700579239')
    var clubmode = ""
    if (options.mode) {
      clubmode = options.mode
    }

    if (options.iswholesale == 1) {
      this.setData({
        ordertype: 17
      })
    } else
    if (options.whproid) {
      this.getwhproinfo(options.whproid)
      this.setData({
        ordertype: 20
      })
    } else
    if (options.inquiry && options.inquiry>=0) {
      this.setData({
        inquiryuid:options.inquiry,
        ordertype: 21
      })
    }
    var clubmust = -1;
    if (options.clubmust) {
      clubmust = options.clubmust
      this.setData({
        clubmust: clubmust
      })
    }




    this.data.iscart = options.iscart
    this.data.hasaddr = options.hasaddr


    if (options.clubid) {
      this.data.clubid = options.clubid
      that.getclubinfo(options.clubid)
    } else {
      that.getmycloubinfo()
    }

    var app = getApp()
    if (options.hasaddr == 1 && addrinfo) {
      var addrinfo = app.globalData.temcart["addrinfo"];
      if (addrinfo["clubinfo"]) {
        app.globalData.clubinfo = addrinfo["clubinfo"]
      }

      if (app.globalData.clubinfo["autarky"] == "-1") {
        navCur = 1;
      } else {
        navCur = 2;
      }

      this.data.clubdelivery = addrinfo.clubdelivery
      if (addrinfo.clubdelivery == 2) {
        this.data.expressaddr = addrinfo.useraddr
      }
    }
    var allowedwh = true; //是否允许放入库存
    if (this.data.ordertype == 20) { //地址发货订单 去掉仓库选项
      allowedwh = false; 
    }else{ //其他订单
      var cartdadta = app.globalData.temcart["data"]
      console.log("cartdadta")
      console.log(cartdadta)

      this.setData({
        allcartdata:cartdadta
      })
      if (cartdadta && cartdadta[0] && cartdadta[0]['cid'] == 3) {
        this.setData({
          ordertype: 15
        })
      }

   

      for (var i in cartdadta) {
        if (cartdadta[i]['presaletime']) {
          if (new Date(cartdadta[i]['presaletime']).getTime() <= Date.parse(new Date())) {
            allowedwh = false;
            break;
          }
        } else {

          allowedwh = false;
          break;
        }
      }

      this.setData({
        cartdadta: cartdadta
      })
      if(this.data.ordertype!=21){
        var Comcouponpro = that.selectComponent("#couponpro")
        Comcouponpro.initcoupon(cartdadta)
      }
    }
  
   
   
    var {
      nav,
      navCur,
      delivery_config,
      paymentmethod,
      paytype
    } = paytool.getnav(config, clubmode, clubmust, this.data.ordertype,allowedwh)
    

    this.setData({
      nav,
      navCur,
      delivery_config,
      paymentmethod,
      paytype
    })



    console.log("this.data.clubdelivery")
    console.log(this.data.clubdelivery)

    that.changnav(this.data.clubdelivery, this.data.expressaddr)

    if (options.iscard == 1) {

      this.setData({
        navCur: -1,
        pageshow: false
      })
    }

    if (options.cardid) {
      this.getcardmodel(options.cardid)
    }
  },
  judgeclubpro(cid,procids){
    if(cid>0){  //存在团
 
      if(!procids){
       procids=['1']
      }
     
      if (procids.indexOf(cid) >=0 ||  procids.indexOf(cid +'') >=0) {
       return true;
     } else {
       return false;
   
     }
 
   }else{
    return true
   }
  },
  //获取相应团长商品
  changeclubpro(cid){
    var allcartdata=this.data.allcartdata;
    if(cid>0){
       var cartdata=[]
       for(var i in allcartdata){
         var item=allcartdata[i];
         console.log("item.customdata")

         console.log(item.customdata)
         var res=this.judgeclubpro(cid,item.customdata?item.customdata.aloneclub.cid:'')
         if(res){
          cartdata.push(item)
         }
       }
       this.setData({
        cartdadta:cartdata
      })
    }else{
      this.setData({
        cartdadta:allcartdata
      })
    }
    this.billpriceinfo();
  },
  //获取仓库商品信息
  getwhproinfo(proid) {
    var that = this;
    order_bill.getwhproinfo(proid).then(function (res) {
      if (res['status'] == 1) {
        var cartdadta = [];
        cartdadta.push(res['obj'])
        that.setData({
          cartdadta: cartdadta
        })
        that.changnav(that.data.clubdelivery, that.data.expressaddr)
      } else {
        that.error(res['message'], true)
      }
    })
  },
  onChangeNum(e) {
    var index = e.currentTarget.dataset.index
    var idx = e.currentTarget.dataset.idx;
    var name = "cartdadta[" + index + "].attrs[" + idx + "].num";
    this.setData({
      [name]: e.detail
    })

  },
  onmodeChange(e) {
    console.log(e)
    this.setData({
      iconmode: e.detail
    })
    this.billpriceinfo()
  },
  selectchange(e) {
    var status = e.detail;
    this.setData({
      pageshow: status
    })
  },
  /**
   * 选择优惠券
   */
  paytypeChange(e) {

    this.setData({
      paytype: e.detail
    })
  },

  //弹出配送时间选择
  showdelivertime() {
    var startDate = Date.parse(new Date());
    var orderconfig = this.data.orderconfig;
    var addtype = orderconfig.deliveryaftertype
    var addtime = orderconfig.deliveryaftertime
    if (addtype == 1) {
      addtime = addtime * 60 * 1000;
    } else if (addtype == 2) {
      addtime = addtime * 60 * 60 * 1000;
    } else if (addtype == 3) {
      addtime = addtime * 60 * 60 * 24 * 1000;
    }
    startDate = startDate + addtime;

    this.setData({
      minDate: startDate,
      chosedtimeshow: true
    })
  },
  ontimeConfirm(event) {


    var date = new Date(event.detail);

    var timedate = this.formatter(date)
    this.setData({
      chosedtimeshow: false,
      delivertime: timedate,
    });
  },
  formatter(date) {
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}`;
  },
  deletetime() {
    if (this.data.delivertime) {
      this.setData({
        delivertime: ""
      })
    }
  },

  updatesimplevipinfo() {
    var that = this;
    actmember.simplevipinfo().then(function (res) {
      if (res["status"] == 1 && res["obj"]) {
        var updatemodel = {}
        updatemodel["memberinfo.goldcoin"] = res["obj"]["goldcoin"]
        updatemodel["memberinfo.amount"] = res["obj"]["amount"]
        updatemodel["memberinfo.vips"] = res["obj"]["vips"]
      }
      that.setData(updatemodel)
    })
  },
  afterlogin(options, configdata, userinfo) {
    this.setData({
      memberinfo: userinfo.memberinfo
    })
    //最新vip会员最新余额
    this.updatesimplevipinfo();
  },
  usecoupon() {
    var that = this;
    this.authop("coupon").then(rest => {
      if (rest["status"] != 1) {
        wx.showToast({
          title: rest["message"] ? rest["message"] : "获取信息失败",
        })
      } else {
        var userinfo = rest["userinfo"]
        var Comcouponpro = that.selectComponent("#couponpro")
        Comcouponpro.showinfo()
      }
    })
  },

  click_nav(e) {
    var that = this;
    this.setData({
      navCur: e.currentTarget.dataset.id,
      freight: 0
    })
    this.changnav()
  },
  changnav(clubdelivery, expressaddr) {

    var navCur = this.data.navCur


    if (navCur == 0 || navCur == 3) {
      this.changeclubpro(0)
      var address = this.selectComponent("#address");
      address.set_init(navCur);


    } else if (navCur == 1 || navCur == 2) {
      this.setData({
        clubdelivery: 0
      })
      var address = this.selectComponent("#clubaddress");
      console.log("11111111111111111111111111")
      console.log(navCur)
      console.log(clubdelivery)
      console.log(expressaddr)

      address.set_init(navCur, clubdelivery, expressaddr);
    }
    this.billpriceinfo();
  },

  //选择优惠券回调
  couponblack(e) {
    var coupon = e.detail
    if (coupon) {
      var discountmoney = actcouponbill.discountmoney(coupon, this.data.cartdadta)
      coupon["discountmoney"] = discountmoney
    }
    this.setData({
      actcoupon: coupon
    })
    this.billpriceinfo()
  },
  setconfig(config) {

    var update = {};
    if (config.yihuo) {
      update['yihuoconfig'] = config.yihuo
    }
    if (config.payment) {
      update['paymentconfig'] = config.payment
      update['unit'] = config.payment.balancepayunit

    }

    if (config.sys_business_config) {
      update['businessconfig'] = config.sys_business_config
    }

    if (config.task) {
      update['taskconfig'] = config.task
      update['taskname'] = config.task.taskname
    }

    var orderconfig = config['order'];
    if (!orderconfig['deliverytimestatus']) {
      orderconfig['deliverytimestatus'] = -1;
    }
    update['orderconfig'] = orderconfig



    if (config.vip) {
      if (config.vip.status == 1) {
        var rank = config.vip.rank;
        update['viprank'] = rank
      }
    }
    if (config.wholesale) {
      update['wholesaleconfig'] = config.wholesale
    }
    this.setData(update)

  },
  judgeorder() {
    var that = this;
    var businessconfig = this.data.businessconfig
    var scenedata = wx.getLaunchOptionsSync()
    this.setData({
      scene: scenedata['scene']
    })

    wx.getSystemInfo({
      success(res) {
        var version = res.SDKVersion;
        version = version.replace(/\./g, "")

        if (version >= 2230) {
          wx.checkBeforeAddOrder({
            success(res) {

              // if (res && res['data'] && ((res['data']['requiredFundType'] != 0) || (businessconfig && businessconfig.wxtransation && businessconfig.wxtransation.teststatus == 1))) {

              //   that.setData({
              //     traceId: res['data']['traceId']
              //   })

              // }
            },
            fail(res) {


            }
          })
        }

      }
    })
  },

  getcardmodel(id) {
    var that = this;
    var cartdadta = this.data.cartdadta
    actpacklistbill.getmodel(id).then(res => {
      if (res['status'] == 1) {
        // html2wxml.html2wxml('article', res.obj.htmlcont, that, 5);



        if (res['obj']['proinfo']) {
          var proinfo = res['obj']['proinfo'];

          var prokeyinfo = {};
          for (var i in proinfo) {

            prokeyinfo[proinfo[i]['id']] = {
              restnum: proinfo[i]['allnum'] - proinfo[i]['usednum'],
              activityprice: proinfo[i]['proinfo']['activityprice']
            }
          }

          res['obj']['prokeyinfo'] = prokeyinfo
        }


        that.setData({
          packinfo: res['obj']
        })
      } else {
        that.error(res['message'], true)
      }

    })
  },
  getclubinfo(id) {


    var that = this
    actmember.getmycloubinfo(id).then(res => {


      if (res["status"] == 1) {
        var clubinfo = res["obj"]
        if (app.globalData.lng) {
          var preslut = acttoolv2.distanceByLnglat(app.globalData.lng, app.globalData.lat, clubinfo.lng, clubinfo.lat)
          clubinfo["juli"] = preslut["formatval"] + preslut["unit"];
        }
        app.globalData.clubinfo = clubinfo;
        that.changnav()
      }
    })


  },
  getmycloubinfo() {
    var app = getApp()
    if (!app.globalData.clubinfo) {
      actmember.getmycloubinfo().then(res => {
        if (res["status"] == 1) {
          var clubinfo = res["obj"]
          if (app.globalData.lng) {
            var preslut = acttoolv2.distanceByLnglat(app.globalData.lng, app.globalData.lat, clubinfo.lng, clubinfo.lat)
            clubinfo["juli"] = preslut["formatval"] + preslut["unit"];
          }
          app.globalData.clubinfo = clubinfo;
        }
      })
    }
    // app.globalData.clubinfo 

  },

  //针对门店配送计算
  shopdeliverychage(ev) {
    var detail = ev.detail
    if (detail.clubdelivery == 1) {
      this.setData({
        clubdelivery: 1,
        freight: 0
      })
      this.data.expressaddr = null
      this.billpriceinfo();
    } else if (detail.clubdelivery == 2) {
      this.setData({
        clubdelivery: 2,
      })
      if (detail.obj) {
        this.calcsamecity(null, detail.obj["distance"])
        this.data.expressaddr = detail.obj
      }
    }
  },
  //同城快递计算
  calcsamecity(intracity, distance) {
    if (!intracity) {
      intracity = this.data.delivery_config.intracity;
    }
    if (!intracity) {
      return;
    }
    if (!distance) {
      var expressaddr = this.data.expressaddr
      distance = expressaddr.distance;
    }
    var {
      calcsamecityinfo,
      freight
    } = paytool.calcsamecity(intracity, distance)
    if (calcsamecityinfo["status"] == 1) {
      this.setData({
        calcsamecityinfo,
        freight
      })
      this.billpriceinfo();
    } else {
      this.data.calcsamecityinfo = calcsamecityinfo;
    }


  },
  //获取运费
  getexpress: function (pro, addr) {

    var that = this;
    if (!pro) {
      pro = this.data.cartdadta
    }
    if (!addr) {
      addr = this.data.expressaddr
    }
    if (pro && addr) {
      if (that.data.navCur == 3) {
        this.calcsamecity();
        return;
      }
      order_bill.getexpress(pro, addr).then(function (paradata) {
        if (paradata.failnum > 0) {} else {
          that.setData({
            freight: paradata.totalmoney
          })
        }
        that.billpriceinfo();
      })
    }
  },
  //改地址切换运费
  selectaddrfunc: function (e) {
    this.data.expressaddr = e.detail;
    if (e.detail != null) {
      this.getexpress(this.data.cartdadta, e.detail)
    }

  },
  //改团点地址切换运费 
  selectgroupaddr: function (e) {
    this.data.actclub = e.detail;
   
    console.log("改团点地址切换运费")
    console.log(e.detail)

    var that = this;

    this.setData({
      freight: 0
    })
    that.billpriceinfo();

    if(e.detail.cid){
      this.changeclubpro(e.detail.cid)
    }
  },
  //计算产品价格
  billpriceinfo: function () {

    var graderank = {};

    if (this.data.memberinfo && this.data.memberinfo.vipinfo) {
      graderank = this.data.memberinfo.vipinfo
    }

    var coindata = null
    if (this.data.ordertype == 15) {
      coindata = {}
      coindata['iconmode'] = this.data.iconmode
      if (this.data.memberinfo) {
        coindata['goldcoin'] = this.data.memberinfo.goldcoin
      } else {
        coindata['goldcoin'] = 0
      }
      if (this.data.taskconfig) {
        if (this.data.taskconfig.coinrate) {
          coindata['coinrate'] = this.data.taskconfig.coinrate
        } else {
          coindata['coinrate'] = 100
        }
        if (this.data.taskconfig.coinmaxrate) {
          coindata['coinmaxrate'] = this.data.taskconfig.coinmaxrate
        } else {
          coindata['coinmaxrate'] = 50
        }
      }
    }

    var {
      prototalprice,
      totalprice,
      pronums,
      paymoney,
      vipcutprice,
      packcutprice,
      cutcoinmoney,
      servicecharge
    } = paytool.billpriceinfo(this.data.cartdadta, this.data.freight, this.data.actcoupon, graderank.rankmoney, this.data.packinfo, coindata, this.data.ordertype, this.data.yihuoconfig)

    console.log("servicecharge")
    console.log(servicecharge)


    this.setData({
      priceinfo: {
        prototalprice,
        totalprice,
        pronums,
        paymoney,
        vipcutprice,
        packcutprice,
        cutcoinmoney,
        servicecharge
      }
    })

    this.selectComponent('#van-submit-bar').updatePrice()
    if (this.data.activitymodel.haslimite) {
      this.autoexcel();
    }

  },
  autoexcel: function () {
    var that = this;
    if (that.data.activitymodel.intervalid != -1) {
      clearInterval(that.data.activitymodel.intervalid)
    }
    that.data.activitymodel.intervalid = setInterval(function () {
      that.setData({
        "list": that.data.list
      });
    }, 1000)
  },
  onchosedtimeClose() {
    this.setData({
      chosedtimeshow: false
    })
  },
  //获取模板消息弹框
  getTemplists() {
    var that = this;
    order_bill.gettemplist().then(function (res) {
      if (res['status'] == 1) {
        that.setData({
          templists: res['obj']
        })
      }
    })
  },
  //1.创建订单  
  createbill: function (e) {

    // ordermodel
    var app = getApp()
    var that = this;
    var ordermodel = {};
    if(!that.data.cartdadta[0]){
      Notify('\n\n商品失效，请重新下单\n');
      return
    }
    //订单内容
    var proinfor = that.data.cartdadta[0];
    if (proinfor['cid'] == 2) { //拼团订单
      if (proinfor['groupid']) {
        ordermodel["groupid"] = proinfor['groupid'];
      }
    }
    if (proinfor['orderid']) {
      ordermodel["orderid"] = proinfor['orderid'];
    }
    var htpro = {};

    if (this.data.ordertype == 17 || this.data.ordertype == 20 || this.data.ordertype == 21) {
      ordermodel["ordertype"] = this.data.ordertype;
      if( this.data.inquiryuid){
        ordermodel["inquiryuid"] = this.data.inquiryuid;
      }

       
      that.data.cartdadta.forEach(function (item) {
        console.log("ppppppppppppppppppppppppppppppppppppppp")
        console.log(item)

        var attrs = {}
        if (item['guigetype'] == 1) {
          for (var i in item['attrs']) {
            var items={
              key: i,
              num: item['attrs'][i]['num']
            }
            if(item['attrs'][i]['realprice']){
              items['realprice']=item['attrs'][i]['realprice'] * 100
            }
            attrs[item['attrs'][i]["index"]] = items
          }
        } else {
          attrs["-1"] = {
            key: -1,
            num: item['attrs'][-1]['num']
          }
        }
        htpro[item["id"]] = attrs
      })
    } else {
      that.data.cartdadta.forEach(function (item) {
        htpro[item["keyval"]] = {
          num: item["num"]
        };
      })
    }
    ordermodel["htpro"] = htpro;

    if (this.data.iconmode) {
      ordermodel['iconmode'] = this.data.iconmode
    }
    var navCur = this.data.navCur

    if (navCur == 0 || navCur == 3) {
      ordermodel["addrinfo"] = this.data.expressaddr // mark: xxx
      ordermodel["distributionmode"] = 1
      if (navCur == 3) {
        ordermodel["distributionmode"] = 8
        var calcsamecityinfo = this.data.calcsamecityinfo
        if (calcsamecityinfo.status !== 1) {
          Notify('\n\n' + calcsamecityinfo.message + '\n');

          return;
        }
      }
      if (!ordermodel["addrinfo"]) {
        Notify('\n\n请选择快递\n');
        return;
      }

    } else if (navCur == 1 || navCur == 2) {
      ordermodel["clubinfo"] = this.data.actclub
      ordermodel["distributionmode"] = 2 * navCur

      if (this.data.clubdelivery == 2) {

        ordermodel["distributionmode"] += 16
        var calcsamecityinfo = this.data.calcsamecityinfo
        if (calcsamecityinfo.status != 1) {
          Notify('\n\n' + calcsamecityinfo["message"] + '\n');
          return;
        } else {
          ordermodel["addrinfo"] = this.data.expressaddr
        }

      }


      if (!ordermodel["clubinfo"]) {
        Notify('\n\n请选择团长\n');
        return
      }

      if ((ordermodel["distributionmode"] & 16) != 16) { //团长自提
        if (this.data.orderconfig.selffetchstatus==1 && this.data.orderconfig.selffetchstatusrequire == 1) {
          if (!app.globalData.userset.pickuptime) {
            var pname = '自取时间'

            Notify('\n\n' + pname + '不能为空\n');
            var clubaddress = this.selectComponent("#clubaddress");
            clubaddress.vliduserset()
            return
          }
        }
        if (this.data.orderconfig.namestatus == 1) {
          if (!app.globalData.userset.name) {
            var pname = this.data.orderconfig.pname ? this.data.orderconfig.pname : '姓名'

            Notify('\n\n' + pname + '不能为空\n');
            var clubaddress = this.selectComponent("#clubaddress");
            clubaddress.vliduserset()
            return
          }
        }

        if (this.data.orderconfig.phonestatus == 1) {
          if ((!app.globalData.userset.phone)) {
            var phonename = this.data.orderconfig.phonename ? this.data.orderconfig.phonename : '手机号'

            Notify('\n\n' + phonename + '手机号码不能为空\n');
            var clubaddress = this.selectComponent("#clubaddress");
            clubaddress.vliduserset()
            return
          }

        }
      }


      ordermodel["userset"] = app.globalData.userset;
    } else if (navCur == -1) {
      ordermodel["distributionmode"] = 0
    } else if (navCur == 4) {
      ordermodel["distributionmode"] = 32

    }

    if (this.data.actcoupon) {
      ordermodel["coupon_id"] = this.data.actcoupon["bindid"]
    }
    var publicdata = ['paytype', 'freight', 'remark'];
    for (var i in publicdata) {
      ordermodel[publicdata[i]] = this.data[publicdata[i]]
    }

    var orderconfig = this.data.orderconfig;
    if (orderconfig.deliverytimestatus == 1 && orderconfig.timerequire == 1 && (!((this.data.navCur == 2 || this.data.navCur == 1) && (this.data.clubdelivery == 1)))) {
      if (!this.data.delivertime) {
        Notify('\n\n请选择配送时间\n');
        return;
      }
    }
    ordermodel['delivertime'] = this.data.delivertime

    ordermodel['scene'] = this.data.scene;
    if (this.data.traceId) {
      ordermodel['traceId'] = this.data.traceId;
    }


    if (navCur == 0 || navCur == 3) {

      if (!this.data.expressaddr.id) {
        var address = this.selectComponent("#address");
        address.noheadformadd(function (relsut) {
          if (relsut["status"] == 1) {
            that.data.expressaddr.id = relsut["obj"].id;
            that.postorder(ordermodel)
          }
        })
        return;
      }
    } else if (navCur == 0 || navCur == 2 && this.data.clubdelivery == 2) {
      if (!this.data.expressaddr.id) {
        var address = this.selectComponent("#clubaddress").selectComponent("#address");
        address.noheadformadd(function (relsut) {
          if (relsut["status"] == 1) {
            that.data.expressaddr.id = relsut["obj"].id;
            that.postorder(ordermodel)
          }
        })
        return;
      }
    }


    if (this.data.packinfo) {
      ordermodel['packlistid'] = this.data.packinfo.id
    }

    this.postorder(ordermodel)

  },
  //2.提交订单
  postorder(ordermodel) {
    var that = this;
    if (app.globalData.share.shareid) {
      ordermodel.fromid = app.globalData.share.shareid
    }

    if (app.globalData.share.taskid) {
      ordermodel.taskid = app.globalData.share.taskid
    }
    var orderconfig = this.data.orderconfig;
    if (orderconfig.beforemakeorder == 1) {
      wx.showModal({
        title: orderconfig.btitle ? orderconfig.btitle : '提示',
        content: orderconfig.bcont ? orderconfig.bcont : '确认下单',
        success(res) {
          if (res.confirm) {
            that.showTemplists(ordermodel)
          } else if (res.cancel) {
            wx.showToast({
              icon: 'none',
              title: '已取消',
            })
          }
        }
      })
    } else {
      that.showTemplists(ordermodel)
    }


  },
  //3.弹出订阅消息框
  showTemplists(ordermodel) {
    var that = this
    var templists = this.data.templists;
    if (templists) {
      var distributionmode = ordermodel['distributionmode'];
      var key = "";
      if (distributionmode == 1) {
        key = "notice_order";
      } else if ((distributionmode & 16) == 16) {
        key = "notice_cluborder_deliver";
      } else {
        key = "notice_cluborder_self";
      }
      var template_ids = []
      if (key && templists[key]) {
        template_ids = templists[key]
      }

      if (template_ids && template_ids.length > 0) {
        if (template_ids.length > 3) {
          template_ids = template_ids.slice(0, 3)
        }

        wx.requestSubscribeMessage({
          tmplIds: template_ids,
          success(res) {},
          fail(res) {},
          complete(res) {
            that.thenpostorder(ordermodel)
          }
        })
      } else {
        that.thenpostorder(ordermodel)

      }


    } else {
      this.thenpostorder(ordermodel)
    }
  },
  //3.传送订单
  thenpostorder(ordermodel) {
    var that = this;
    that.setData({
      submitstatus: true
    })

    order_bill.createorder(ordermodel).then(function (restmodel) {
      if (that.data.iscart == 1) {
        if (ordermodel['ordertype'] == 17) {
          wsactcart.removeselected();
        } else {
          actcart.removeselected();
         
        }
      }
      if (restmodel["status"] == 1) {


        if (restmodel["paytype"] == 8) {
          wx.redirectTo({
            url: '/xc_lshop/shop/paycore/payhelp/infor?orderid=' + restmodel['id'],
          })
        } else if (restmodel["paytype"] == 1 || restmodel["paytype"] == 3) {
          var pay_params = restmodel["pay_params"];


          if (ordermodel['traceId']) {

            wx.requestOrderPayment({
              timeStamp: pay_params["timeStamp"],
              nonceStr: pay_params["nonceStr"],
              package: pay_params["package"],
              signType: pay_params['signType'],
              paySign: pay_params["paySign"],
              success(res) {



                order_bill.queryorder(restmodel["id"]).then(function (queryreslut) {

                  if (queryreslut["status"] == 1) {
                    // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])
                    wx.redirectTo({
                      url: '/xc_lshop/shop/paycore/paysuccess?id=' + restmodel["id"],
                    })
                  }
                })
                that.setData({
                  submitstatus: false
                })
              },
              fail(res) {

                if (res["errMsg"] == "requestPayment:fail cancel") {
                  wx.showModal({
                    title: '订单未支付',
                    content: '订单未支付',
                    showCancel: false,
                    success(res) {


                      wx.redirectTo({
                        url: "../order/index?opstatus=-1",
                      })
                    }
                  })
                }
                that.setData({
                  submitstatus: false
                })
              }
            })
          } else {
            wx.requestPayment({
              timeStamp: pay_params["timeStamp"],
              nonceStr: pay_params["nonceStr"],
              package: pay_params["package"],
              signType: pay_params['signType'],
              paySign: pay_params["paySign"],
              success(res) {
                // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])

                order_bill.queryorder(restmodel["id"]).then(function (queryreslut) {
                  if (queryreslut["status"] == 1) {
                    wx.redirectTo({
                      url: '/xc_lshop/shop/paycore/paysuccess?id=' + restmodel["id"],
                    })
                    // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])

                  }
                })
                that.setData({
                  submitstatus: false
                })
              },
              fail(res) {
                if (res["errMsg"] == "requestPayment:fail cancel") {
                  wx.showModal({
                    title: '订单未支付',
                    content: '订单未支付',
                    showCancel: false,
                    success(res) {


                      wx.redirectTo({
                        url: "../order/index?opstatus=-1",
                      })
                    }
                  })
                }
                that.setData({
                  submitstatus: false
                })
              }
            })
          }

        } else if (restmodel["paytype"] == 2 || restmodel["paytype"] == 0) {
          //余额支付
          wx.redirectTo({
            url: '/xc_lshop/shop/paycore/paysuccess?id=' + restmodel["id"],
          })
          // that.showtemplate(template_ids, restmodel['ordernum'], restmodel["id"])
          that.setData({
            submitstatus: false
          })
        }
      } else {
        wx.showModal({
          title: '错误',
          content: restmodel["message"],
        })
        that.setData({
          submitstatus: false
        })
      }
    })
  },
  showtemplate(template_ids, ordernum, id) {
    var that = this;
    console.log("ddddddddddddddddddddddddddddddddddddddddddddddd")
    console.log(template_ids)

    if (template_ids && template_ids.length > 0) {
      if (template_ids.length > 3) {
        template_ids = template_ids.slice(0, 3)
      }

      wx.requestSubscribeMessage({
        tmplIds: template_ids,
        success(res) {
          console.log("success9999999999999999999")
          console.log(res)
          that.sendnotice_buy(ordernum)
        },
        fail(res) {
          console.log("fail8888888888888888888888")
          console.log(res)

        },
        complete(res) {

          wx.redirectTo({
            url: '/xc_lshop/shop/paycore/paysuccess?id=' + id,
          })
        }
      })
    } else {

      wx.redirectTo({
        url: '/xc_lshop/shop/paycore/paysuccess?id=' + id,
      })
    }
  },
  sendnotice_buy(ordernum) {
    order_bill.sendnotice_buy(ordernum).then(function (restmodel) {
      console.log(restmodel)
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //系统组件选择地址回调
    const location = chooseLocation.getLocation();
    if (location) {
      var address = null
      if (this.data.navCur == 0 || this.data.navCur == 3) {

        address = this.selectComponent("#address");
      } else if (this.data.navCur == 1 || this.data.navCur == 2) {


        address = this.selectComponent("#clubaddress");
      }


      address.chooseLocation(location)

    }
  },
  onUnload() {
    // 页面卸载时设置插件选点数据为null，防止再次进入页面，geLocation返回的是上次选点结果
    chooseLocation.setLocation(null);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


})